const User = require("../model/userModel")
const bcrypt = require("bcrypt")

module.exports.register = async (req, res, next) => {
  try {
    const { username, email, password } = req.body

    // 查找是否存在用户名重名，返回值为对象
    const usernameCheck = await User.findOne({ username })
    if (usernameCheck) {
      return res.json({ status: false, msg: "Username already used." })
    }

    const emailCheck = await User.findOne({ email })
    if (emailCheck) {
      return res.json({ status: false, msg: "Email already used." })
    }

    const salt = await bcrypt.genSalt(10)
    const hashedPassword = await bcrypt.hash(password, salt)
    const user = await User.create({
      email,
      username,
      password: hashedPassword,
    })

    delete password
    return res.json({ status: true, user })
  } catch (ex) {
    next(ex)
  }
}

module.exports.login = async (req, res, next) => {
  try {
    const { username, password } = req.body

    // 查找是否存在用户名重名，返回值为对象
    const user = await User.findOne({ username })
    if (!user) {
      return res.json({ status: false, msg: "Incorrect username or password." })
    }

    const isPasswordValid = await bcrypt.compare(password, user.password)
    if (!isPasswordValid) {
      return res.json({ status: false, msg: "Incorrect username or password." })
    }

    delete user.password
    return res.json({ status: true, user })
  } catch (ex) {
    next(ex)
  }
}

module.exports.setAvatar = async (req, res, next) => {
  try {
    const userId = req.params.id
    const avatarImage = req.body.image

    // 查找是否存在用户名重名，返回值为对象
    const user = await User.findByIdAndUpdate(
      userId,
      {
        isAvatarImageSet: true,
        avatarImage,
      },
      // 默认为 false, 表示是否返回修改后的数据
      { new: true }
    )
    return res.json({ status: user.isAvatarImageSet, image: user.avatarImage })
  } catch (ex) {
    next(ex)
  }
}

module.exports.getAllUsers = async (req, res, next) => {
  try {
    const userId = req.params.id

    const users = await User.find({
      _id: {
        // 查找所有 _id 不为 userId 的记录
        $ne: userId,
      },
      isAvatarImageSet: {
        $eq: true,
      },
    }).select(["_id", "username", "avatarImage", "email"])
    return res.json({ status: true, users: users })
  } catch (ex) {
    next(ex)
  }
}
